/**
 * Created with IntelliJ IDEA.
 * User: aermakov
 * Date: 23.05.13
 * Time: 15:22
 * To change this template use File | Settings | File Templates.
 */

Ext.ns('GrailsCompany.form');

GrailsCompany.form.CRUDFormPanel = Ext.extend(Ext.form.FormPanel, {

    crudacceptable: true,

    multiTabs: false,

    constructor: function (config) {
        config = Ext.apply({
            autoDestroy: false,
            monitorValid: true,
            border: false,
            defaultType: 'textfield'
        }, config);

        if (config.actions) {
            if (!config.buttons) {
                config.buttons = [];
            }
            Ext.each(config.actions, function(action) {
                config.buttons.push({
                    xtype: 'formbutton',
                    text: action.caption ? action.caption : Ext.util.Format.capitalize(action),
                    action: action.action ? action.action : action
                });
            }, this);
        }

        this.addEvents({
            'done': true,
            'crudbatch': true
        });

        this.on('action', this.handleCRUDAction);

        GrailsCompany.form.CRUDFormPanel.superclass.constructor.call(this, config);
    },

    handleCRUDAction: function (action) {
        var values = this.getForm().getValues();
        var crud = ['create', 'read', 'update', 'delete'];
        if (this.multiTabs && crud.indexOf(action) > -1 && action !== 'delete') {
            this.fireEvent('crudbatch', this.storeId, this.recordId, action, values);
            return;
        }

        switch (action) {
            case 'update':
                DH.update(this.storeId, this.recordId, values);
                break;
            case 'delete':
                DH.delete(this.storeId, this.recordId);
                this.getForm().reset();
                break;
            case 'create':
                DH.create(this.storeId, values);
                break;
        }

        this.fireEvent('done', action);
    }
});
Ext.reg('crudform', GrailsCompany.form.CRUDFormPanel);